#import "SEGMenulist2Manager.h"

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

#if __has_include(<Commom/SEGHTTPBusinessManager.h>)
#import <Commom/SEGHTTPBusinessManager.h>
#else
#import "SEGHTTPBusinessManager.h"
#endif

#if __has_include(<SEGPlatform/SEGPlatformManager.h>)
#import <SEGPlatform/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

#if __has_include(<SEGPlatform/SEGProfileManager.h>)
#import <SEGPlatform/SEGProfileManager.h>
#else
#import "SEGProfileManager.h"
#endif

#if __has_include(<SEGPlatform/SEGBussinessConstHeader.h>)
#import <SEGPlatform/SEGBussinessConstHeader.h>
#else
#import "SEGBussinessConstHeader.h"
#endif

#if __has_include(<CommonMediator/SEGMediatorHeader.h>)
#import <CommonMediator/SEGMediatorHeader.h>
#else
#import "SEGMediatorHeader.h"
#endif

#if __has_include(<SEGMenus/SEGMenuListCacheManager.h>)
#import <SEGMenus/SEGMenuListCacheManager.h>
#else
#import "SEGMenuListCacheManager.h"
#endif

#import "ReactiveObjC.h"

static id _menuList2Manager;
static dispatch_once_t onceToken;

@implementation SEGMenulist2Manager
#pragma mark - SINGLE----BEGIN----
+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _menuList2Manager = [[self alloc] init];
    });
    return _menuList2Manager;
}

+(void)destroyResource{
    onceToken = 0;
    _menuList2Manager = nil;
}

#pragma mark - SINGLE----END----

#pragma mark - HTTP----BEGIN----
-(void)requestMenulist2WithMenuversion:(NSString *)menuVersion
                               menuSid:(NSString *)menuSid
                               appCode:(NSString *)appCode
                            settingsId:(NSString *)settingsId
                                action:(NSString *)action
                             completed:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed {
    
    NSString *urlString = nil;
    NSMutableDictionary *params = [@{@"menuVersion":@"1", @"appCode":appCode} mutableCopy];
    
    if ([action isEqualToString:kActionCOMMON_MENULIST]) { // 常用菜单
        urlString = [SEGServerManager serverUrlJoint:kClientRootURL, @"/bms-api/menu-api/commonMenuList", nil];
    } else { // tab菜单
        [params setValue:menuSid forKey:@"menuSid"];
        [params setValue:settingsId forKey:@"settingsId"];
        urlString = [SEGServerManager serverUrlJoint:kClientRootURL, @"/bms-api/menu-api/menuList2", nil];
    }
    
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:params completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        completed(isSuccessed,result,codeType,error.localizedDescription);
        return;
    }];
}

/**
 * 获取服务器底部Tab菜单数据
 * @author Sam
 * @version 4.6.0
 */
-(void)segRequestMenuListForTabBarCompleted:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{
    [self requestMenulist2WithMenuversion:@"0" menuSid:@"0" appCode:kAppPlatformCode settingsId:@"0" action:@"0" completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        NSArray<SEGMenuListModel*>* data = [self segResponseMenuWithAction:@"Tab" isSuccessed:isSuccessed result:result codeType:codeType errorMessage:errorMessage];
        
        if (!data && data.count <= 0) {
            completed(NO,nil,codeType,errorMessage);
            return;
        }
        
        //保存菜单父子级关系，用于打红点
        [[SEGUhomeMediator sharedInstance] seg_saveMenuList:@{@"array":data,@"parentsSid":@"0"}];
        
        NSMutableArray *dataArray = [NSMutableArray new];
        //支持的用户类型
        [data enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSArray *userTypeArr = [obj.userType componentsSeparatedByString:@"|"];
            //包含用户自己的用户类型 就添加
            if ([userTypeArr containsObject:[SEGProfileManager sharedManager].profile.type]) {
                [dataArray addObject:obj];
            }
        }];
        self.menuListTab = [dataArray copy];
        completed(YES,result,codeType,errorMessage);
        return;
    }];
}

/**
 * 菜单数据请求回调
 * @author Sam
 * @version 4.6.0
 */
-(NSArray<SEGMenuListModel*>*)segResponseMenuWithAction:(NSString*)action isSuccessed:(BOOL)isSuccessed result:(id)result codeType:(NSString*)codeType errorMessage:(NSString*)errorMessage{
    NSArray<SEGMenuListModel*> *ret = [NSArray array];
    
    //请求失败，获取本地数据
    if (!isSuccessed) {
        if ([action isEqualToString:kActionCOMMON_MENULIST]) {
            ret = [SEGMenuListCacheManager menuCache_getAllCommonMenuListData];
        } else {
            ret = [self segGetMenuListDataWithLocalPath:action];
        }
        return ret;
    }
    
    //请求成功
    NSMutableArray<SEGMenuListModel*> *arrM = [NSMutableArray array];
    
    NSArray *data = [[result allKeys]containsObject:@"data"] ? [result valueForKey:@"data"] : nil;
    if (data && [data isKindOfClass:[NSArray class]]) {
 
     for (NSDictionary *object in data) {
            if (object && [object isKindOfClass:[NSDictionary class]]) {
                SEGMenuListModel *data = [SEGMenuListModel yy_modelWithDictionary:object];
                
                if ([action isEqualToString:@"Tab"]) { //如果是底部Tab数据，只添加action位Tab的数据
                    if ([data.action rangeOfString:@"TAB_"].location != NSNotFound && ![data.action isEqualToString:@"TAB_UGC"]) {
                        [arrM addObject:data];
                    }
                }else{
                    [arrM addObject:data];
                }
            }
        }
            
     }
    
    //网络请求成功，请求到数据，保存到本地并且返回
    if(arrM.count > 0){
        
        // 常用菜单不用排序, 和安卓端保持一致
        if ([action isEqualToString:kActionCOMMON_MENULIST]) {
            [SEGMenuListCacheManager menuCache_saveAllCommonMenuListWithData:arrM];
            return arrM;
        }
        
        /*25738 【深到家v1.1.0】iOS 主tab排序未按照rn值进行排列*/
        NSComparator cmptr = ^(SEGMenuListModel * obj1, SEGMenuListModel * obj2) {
            if ([obj1.rn integerValue] > [obj2.rn integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            if ([obj1.rn integerValue] < [obj2.rn integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        };
        NSArray *dataSort = [arrM sortedArrayUsingComparator:cmptr];
        ret = [NSArray arrayWithArray:dataSort];
        [self segSaveMenuListData:dataSort localPath:action];
        return ret;
    }
    
    // !!!:  Wendy，2019.3.20, 服务器获取到空数据就显示空的，不再读取本地 4.9.2版本修改
    //    //网络请求成功，请求到空数据,获取本地缓存数据
    //    ret = [self segGetMenuListDataWithLocalPath:action];
    return ret;
}

#pragma mark - 菜单缓存操作
/**
 * 保存菜单数据
 * @author Sam
 */
-(void)segSaveMenuListData:(NSArray<SEGMenuListModel*>*)data localPath:(NSString*)action{
    if (!data || data.count <= 0) return;
    [NSKeyedArchiver archiveRootObject:data toFile:[self segpgcMenuPath:action]];
}

/**
 * 获取菜单数据
 * @author Sam
 */
-(NSArray<SEGMenuListModel*>*)segGetMenuListDataWithLocalPath:(NSString*)action{
    NSArray<SEGMenuListModel*>* ret = [NSKeyedUnarchiver unarchiveObjectWithFile:[self segpgcMenuPath:action]];
    if ([action isEqualToString:@"Tab"]) {
        /*到家汇1.7.0，4.7.0，Sam，菜单通过rn进行升序排序*/
        NSComparator cmptr = ^(SEGMenuListModel * obj1, SEGMenuListModel * obj2){
            if ([obj1.rn integerValue] > [obj2.rn integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1.rn integerValue] < [obj2.rn integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        };
        
        return [ret sortedArrayUsingComparator:cmptr];
    }
    return ret;
}

-(NSString*)segpgcMenuPath:(NSString*)action{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"menu%@%@.data",action,kAccountUserID]];
}
#pragma mark - HTTP----END----

/// 遍历菜单获取网页账单URL
- (id)getWebBillPayURL {
    __block BOOL isExistWebBillPay = NO;
    __block NSString *action = @"";
    // 1.遍历tab
    [[SEGMenulist2Manager sharedManager].menuListTab enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull tabMenuModel, NSUInteger idx, BOOL * _Nonnull stop) {
        // 2.遍历tab对应菜单
        NSArray<SEGMenuListModel*> *menuList = [self segGetMenuListDataWithLocalPath:tabMenuModel.action];
        [menuList enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull menuModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if (menuModel.isWebBillPay.integerValue == 1) {
                isExistWebBillPay = YES;
                action = menuModel.action;
                *stop = YES;
            }
            // 遍历子菜单
            [menuModel.childList enumerateObjectsUsingBlock:^(SEGMenuListModel * _Nonnull childMenu, NSUInteger idx, BOOL * _Nonnull stop) {
                if (childMenu.isWebBillPay.integerValue == 1) {
                    isExistWebBillPay = YES;
                    action = childMenu.action;
                    *stop = YES;
                }
            }];
            if (isExistWebBillPay) {
                *stop = YES;
            }
        }];
        if (isExistWebBillPay) {
            *stop = YES;
        }
    }];
    return RACTuplePack(@(isExistWebBillPay), action);
}

#pragma mark - GETTER----BEGIN----
-(NSArray<SEGMenuListModel*> *)menuList2{
    if (!_menuList2) {
        _menuList2 = [[NSArray alloc]init];
    }
    return _menuList2;
}


#pragma mark - GETTER----END----
@end
